package com.shike.core.utils.redis;

import com.google.common.collect.Lists;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;

import java.util.Set;
import java.util.concurrent.TimeUnit;

@Configuration
public class RedisUtil<T> {
    private RedisTemplate<String, T> redisTemplate;
    private ValueOperations<String, T> valueOperations;

    @Autowired
    RedisUtil(RedisTemplate<String, T> redisTemplate) {
        this.redisTemplate = redisTemplate;
        this.valueOperations = redisTemplate.opsForValue();
    }

    /**
     * 设置值, 以分钟为单位
     *
     * @param prefix
     * @param key
     * @param value
     */
    public void putValue(KeyPrefix prefix, Object key, T value) {
        valueOperations.set(prefix.getPrefix() + key, value, prefix.expireSeconds(), TimeUnit.SECONDS);
    }

    /* *
     * 根据前缀获取值
     * @author cyh
     * @date 2020-03-15
     * @param prefix: 前缀
     * @param key: key值
     * @return T
     */
    public T getValue(KeyPrefix prefix, Object key) {
        return valueOperations.get(prefix.getPrefix() + key);
    }


    /* *
     * 根据key类配置的时间来延长时间
     * @author cyh
     * @date 2020-03-15
     * @param redisKey:
     * @param key:
     * @return void
     */
    public void setExpire(KeyPrefix prefix, Object key) {
        redisTemplate.expire(prefix.getPrefix() + key, prefix.expireSeconds(), TimeUnit.SECONDS);
    }

    /**
     * 判断key是否存在
     *
     * @param redisKey
     * @param key
     * @return
     */
    public Boolean exists(KeyPrefix redisKey, Object key) {
        return redisTemplate.countExistingKeys(Lists.newArrayList(redisKey.getPrefix() + key)) > 0;
    }


    /**
     * 根据key进行匹配,得到多条结果
     *
     * @param redisKey
     * @param keyPattern
     * @return
     */
    public Set<String> keys(KeyPrefix redisKey, String keyPattern) {
        return redisTemplate.keys(redisKey.getPrefix() + keyPattern);
    }

    /**
     * 删除key
     *
     * @param redisKey
     * @param key
     */
    public void delete(KeyPrefix redisKey, String key) {
        redisTemplate.delete(redisKey.getPrefix() + key);
    }

}